
var FoldersController = function() {
}

FoldersController.prototype = {
	model : null, // Will be set by jMVC

	toggleNode : function(node) {
		node.collapsed = !node.collapsed;
	},

	selectNode : function(node) {
		var selected = this.findSelectedNode();
		if(selected)
			selected.selected = false;
		var editing = this.findEditingNode();
		if(editing)
			editing.editing = false;
		if(node)
			node.selected = true;
	},

	addNode : function() {
		var parent = this.findSelectedNode();
		var newChild = { name: "New folder", children: [] };
		parent.children[parent.children.length] = newChild;
		this.selectNode(newChild);
		this.renameNode(newChild);
	},

	deleteNode : function() {
		var node = this.findSelectedNode();
		var parent = this.findParent(node);
		if(parent)
			for(var i = 0; i < parent.children.length; i++)
				if(parent.children[i] == node)
					parent.children.splice(i, 1);
	},

	renameNode : function() {
		this.findSelectedNode().editing = true;
	},

	applyRename : function(newName) {
	    if(newName != "") {
		    var node = this.findSelectedNode();
		    node.name = newName;
		    node.editing = false;
		} 
		else
		    alert("Please enter a name");
	},
	
	canDeleteSelectedNode : function() {
	    var selectedNode = this.findSelectedNode();
	    if(!selectedNode)
	        return false; // Can't delete if nothing's selected
	    else if(selectedNode == this.model.folders)
	        return false; // Don't let them delete the root folder
	    else
	        return true;
	},
	
	hasSelection : function() {
	    return this.findSelectedNode() != null;
	},
	
	findSelectedNode : function() {
		return this.findNode(this.model.folders, function(node) { return node.selected; });
	},

	findEditingNode : function() {
		return this.findNode(this.model.folders, function(node) { return node.editing; });
	},

	findNode : function(root, criteria) {
		if(criteria(root)) return root;
		for(var i = 0; i < root.children.length; i++) {
			var match = this.findNode(root.children[i], criteria);
			if(match) return match;
		}
		return null;
	},

	findParent : function(node, root) {
		if(!root) root = this.model.folders;
		for(var i = 0; i < root.children.length; i++)
			if(root.children[i] == node)
				return root;
		for(var i = 0; i < root.children.length; i++) {
			var parent = this.findParent(node, root.children[i]);
			if(parent) 
				return parent;
		}	
		return null;
	}	
};